#include "threadcondition.h"
#include <time.h>
#include <errno.h>

ThreadCondition::ThreadCondition(MutexLock & lock):lock(lock)
{
    pthread_cond_init(&this->condition, nullptr);
}

ThreadCondition::~ThreadCondition()
{
    pthread_cond_destroy(& this->condition);
}

void ThreadCondition::wait()
{
    pthread_cond_wait(&this->condition, this->lock.get());
}

void ThreadCondition::notify()
{
    pthread_cond_signal(& this->condition);
}

void ThreadCondition::notifyAll()
{
    pthread_cond_broadcast(& this->condition);
}

bool ThreadCondition::waitForSecond(unsigned int seconds)
{
    struct timespec second;

    // 获取系统时钟 CLOCK_REALTIME 实时时钟
    clock_gettime(CLOCK_REALTIME, & second);

    second.tv_sec += seconds;

    return ETIMEDOUT == pthread_cond_timedwait(& this->condition, this->lock.get(), &second);
}
